package com.aiit.config;

import com.aiit.service.impl.PermissionService;
import com.aiit.service.impl.RoleService;
import com.aiit.service.impl.UserService;
import com.aiit.pojo.Permission;
import com.aiit.pojo.Role;
import com.aiit.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

@Slf4j
public class MyRealm<Int> extends AuthorizingRealm {
    ByteSource salt;
    String encodedPassword = null;
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    int userId;
    // 获取授权信息--权限校验，我们访问的资源被过滤器规则拦截且需要角色或权限验证时

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = principals.getPrimaryPrincipal().toString();
        Set<Role> roles = roleService.findRoleListByUserId(userId);
        Set<Permission> permissions = permissionService.findPermissionListByUserId(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        for (Role role : roles) {
            log.info("角色--------->" + role.getRolename());
            info.addRole(role.getRolename());

        }
        for (Permission perm : permissions) {
            log.info("权限--------->" + perm.getPermissioncode());
            info.addStringPermission(perm.getPermissioncode());
        }
        return info;
    }

    // 获取认证信息--身份认证，我们调用subject.login()时调用
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的用户名密码
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        log.info("===========>>>>>————身份认证————");
        User user = userService.selectUserName(username);//获取数据库中该用户的信息
        //System.out.println(user);
        if (user != null) {

            userId = user.getUserid();
            //取出盐并编码
            salt = ByteSource.Util.bytes(user.getSalt());
            encodedPassword = ShiroEncryption.shiroEncryption(password, user.getSalt()); //加盐的密码
        }
        /*        log.info("加密的密码为============>>>>>"+encodedPassword);*/
        if (user == null) {
            throw new UnknownAccountException();
        }
        if (!encodedPassword.equals(user.getPassword())) {
            throw new IncorrectCredentialsException();
        }
        String md5Pwd = new Md5Hash(username, password).toHex();
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                username,//用户输入的用户名密码
                password,
                salt,
                this.getName()  // realm的标识
        );
        return simpleAuthenticationInfo;

    }


}
